import React, { useState, useEffect } from 'react';
import { Modal, Image, List, message, InputNumber, Space } from 'antd';
import { websiteService, ImageItem } from '@/services/websiteService';
import styles from './index.module.css';

interface ImageSelectorProps {
  visible: boolean;
  onClose: () => void;
  onSelect: (url: string) => void;
  imageSize: {
    width: number;
    height: number;
  };
  onSizeChange: (type: 'width' | 'height', value: number | null) => void;
}

const ImageSelector: React.FC<ImageSelectorProps> = ({
  visible,
  onClose,
  onSelect,
  imageSize,
  onSizeChange,
}) => {
  const [images, setImages] = useState<ImageItem[]>([]);
  const [loading, setLoading] = useState(false);

  const fetchImages = async () => {
    try {
      setLoading(true);
      const images = await websiteService.getImages();
      setImages(images);
    } catch (error) {
      message.error('获取图片列表失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    if (visible) {
      fetchImages();
    }
  }, [visible]);

  const handleSelect = (image: ImageItem) => {
    onSelect(image.url);
    onClose();
  };

  return (
    <Modal
      title="选择图片"
      open={visible}
      onCancel={onClose}
      footer={null}
      width={800}
    >
      <div className={styles.sizeControls}>
        <Space>
          <span>图片宽度：</span>
          <InputNumber
            min={100}
            max={1000}
            value={imageSize.width}
            onChange={(value) => onSizeChange('width', value)}
          />
          <span>px</span>
          <span>图片高度：</span>
          <InputNumber
            min={100}
            max={1000}
            value={imageSize.height}
            onChange={(value) => onSizeChange('height', value)}
          />
          <span>px</span>
        </Space>
      </div>
      <List
        loading={loading}
        grid={{ gutter: 16, column: 4 }}
        dataSource={images}
        renderItem={(image) => (
          <List.Item>
            <div 
              className={styles.imageItem}
              onClick={() => handleSelect(image)}
            >
              <Image
                src={image.url}
                alt={image.filename}
                preview={false}
                style={{
                  width: imageSize.width,
                  height: imageSize.height,
                  objectFit: 'contain'
                }}
              />
              <div className={styles.imageInfo}>
                <div className={styles.filename}>{image.filename}</div>
                <div className={styles.time}>{image.upload_time}</div>
              </div>
            </div>
          </List.Item>
        )}
      />
    </Modal>
  );
};

export default ImageSelector; 